package com.imooc.security.hmac;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/*

其他消息摘要算法的实现
RipeMD
Tiger
Whirlpool
GOST3411

Bouncy Castle实现

 */
public class ImoocHmac {

    public static String src = "imooc security hmac";

    public static void main(String[] args) {
        jdkHmacMD5();
        bcHmacMD5();
    }

    private static void jdkHmacMD5() {
        try {
            KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacMD5");
            SecretKey secretKey =keyGenerator.generateKey();
            byte[] key=secretKey.getEncoded();
            key=Hex.decodeHex(new char[]{'a','a','a','a','a','a','a','a','a','a'});
            SecretKey restoreSecretKey = new SecretKeySpec(key,"HmacMD5");
            Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());
            mac.init(restoreSecretKey);
            byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());
            System.out.println("jdk hmacMD5: "+ Hex.encodeHexString(hmacMD5Bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void bcHmacMD5() {
        try {
            HMac hmac=new HMac(new MD5Digest());
            hmac.init(new KeyParameter((org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa"))));
            hmac.update(src.getBytes(),0,src.getBytes().length);

            byte[] hmacMD5Bytes=new byte[hmac.getMacSize()];
            hmac.doFinal(hmacMD5Bytes,0);

            System.out.println("bc hmacMD5: "+ org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
